<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑用户' : '新增用户'"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      class="user-form"
    >
      <el-form-item label="头像">
        <div class="avatar-upload">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
          >
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="avatar-tip">
            支持 jpg、png 格式，文件大小不超过 2MB
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="formData.username"
          placeholder="请输入用户名"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item v-if="!isEdit" label="密码" prop="password">
        <el-input
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          maxlength="50"
          show-password
        />
      </el-form-item>
      
      <el-form-item label="角色" prop="role">
        <el-select
          v-model="formData.role"
          placeholder="请选择角色"
          style="width: 100%"
        >
          <el-option label="管理员" :value="0" />
          <el-option label="前台用户" :value="1" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createUser, updateUser } from '../../../api/user'
import { uploadAvatar, validateImageFile } from '../../../utils/upload'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 表单引用
const formRef = ref()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 是否为编辑模式
const isEdit = computed(() => !!props.userData?.id)

// 提交加载状态
const submitLoading = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  username: '',
  password: '',
  avatar: '',
  role: 1,
  status: 1
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 50, message: '密码长度在 6 到 50 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 上传配置
const uploadAction = ref('') // 实际不会用到，因为我们手动处理上传
const uploadHeaders = computed(() => ({
  'Authorization': localStorage.getItem('token')
}))

// 头像上传前验证
const beforeAvatarUpload = async (file) => {
  // 使用统一的验证函数
  const validation = validateImageFile(file, {
    maxSize: 2,
    allowedTypes: ['image/jpeg', 'image/png', 'image/jpg']
  })
  
  if (!validation.valid) {
    validation.errors.forEach(error => {
      ElMessage.error(error)
    })
    return false
  }

  // 手动处理上传
  handleUpload(file)
  return false // 阻止默认上传
}

// 手动处理上传
const handleUpload = async (file) => {
  try {
    const response = await uploadAvatar(file)
    if (response.code === 200) {
      formData.avatar = response.data
      ElMessage.success('头像上传成功')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 上传成功回调（实际不会触发，因为我们手动处理）
const handleAvatarSuccess = () => {
  // 预留
}

// 上传失败回调
const handleAvatarError = () => {
  ElMessage.error('头像上传失败')
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    username: '',
    password: '',
    avatar: '',
    role: 1,
    status: 1
  })
  formRef.value?.resetFields()
}

// 关闭对话框
const handleClose = () => {
  resetForm()
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const submitData = { ...formData }
    
    let response
    if (isEdit.value) {
      // 编辑时不需要密码字段
      delete submitData.password
      response = await updateUser(submitData)
    } else {
      response = await createUser(submitData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      emit('success')
      handleClose()
    }
  } catch (error) {
    console.error('提交失败:', error)
    if (error !== 'validation failed') {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 监听用户数据变化，填充表单
watch(() => props.userData, (newData) => {
  if (newData) {
    Object.assign(formData, {
      id: newData.id,
      username: newData.username,
      password: '',
      avatar: newData.avatar || '',
      role: newData.role,
      status: newData.status
    })
  }
}, { immediate: true })

// 监听对话框打开，重置表单
watch(dialogVisible, (visible) => {
  if (!visible) {
    resetForm()
  }
})
</script>

<style scoped>
.user-form {
  padding: 0 20px;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 120px;
  height: 120px;
  display: inline-block;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.avatar-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-upload) {
  display: block;
  width: 120px;
  height: 120px;
}
</style>
